# -*- coding: utf-8 -*-
# @Time    : 2024/9/3 17:54
# @Author  : yujiahao
# @File    : my_feishusheet_demo.py
# @description: 调用飞书表格API 简单写入demo
# 详情参考飞书文档：https://open.feishu.cn/document/home/sales-statistics-base-on-spreadsheets/sales-statistics-based-on-sheets


import requests
import json

# 飞书 API 基本信息
app_id = '从应用中获取'
app_secret = '从应用中获取'
spreadsheet_token = '表的token'
sheet_id = '表的sheetID，不是sheet名称'


# 获取 Tenant Access Token
def get_access_token(app_id, app_secret):
    url = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal'
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    payload = {
        'app_id': app_id,
        'app_secret': app_secret
    }
    response = requests.post(url, headers=headers, data=json.dumps(payload))
    if response.status_code == 200:
        return response.json().get('tenant_access_token')
    else:
        raise Exception(f'获取访问令牌失败: {response.text}')


# 要写入的数据
data = {
    "values": [
        ["Hello", 1],
        ["World", 2]
    ]
}


# 写入数据到表格(追加) 详情可参考：https://open.feishu.cn/document/server-docs/docs/sheets-v3/data-operation/append-data
def write_data_to_sheet(access_token, spreadsheet_token, sheet_id, data):
    url = f'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheet_token}/values_append'
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    payload = {
        'valueRange': {
            'range': f'{sheet_id}!A2:AH',  # 确保范围正确
            'values': data['values']
        }
    }

    # 打印请求信息
    print(f"URL: {url}")
    print(f"Headers: {headers}")
    print(f"Payload: {json.dumps(payload, indent=2)}")

    response = requests.post(url, headers=headers, data=json.dumps(payload))
    if response.status_code == 200:
        response_json = response.json()
        if response_json.get('code') == 0:
            print('数据写入成功')
        else:
            print(f'数据写入失败: {response_json}')
    else:
        print(f'数据写入失败: {response.status_code} - {response.text}')


# 主程序
if __name__ == '__main__':
    try:
        access_token = get_access_token(app_id, app_secret)
        write_data_to_sheet(access_token, spreadsheet_token, sheet_id, data)
    except Exception as e:
        print(e)
